﻿CREATE PROCEDURE [dbo].[usp_select_Faults2]
(
	@FaultID			varchar(50)		 = NULL
   ,@Application		varchar(50)      = NULL   
   ,@StartDate			Datetime	      = NULL   
   ,@EndDate			Datetime	      = NULL   
   ,@FaultCode			varchar(50)      = NULL   
   ,@FailureCategory	varchar(50)      = NULL
   ,@ErrorType			varchar(50)      = NULL 
   ,@MaxFaultSeverity	int				 = 4
   ,@Debug              bit              = 0
)
AS

SET NOCOUNT ON;

-- Bootstrap
DECLARE @DebugPrefix       varchar(10)
DECLARE @ErrorCode         int

SET @ErrorCode          = 0;
SET @DebugPrefix        = '>>> DEBUG: '


-- Print parameters
IF (@Debug > 0)
BEGIN
   PRINT @DebugPrefix + '@FaultID = ' + @FaultID
   PRINT @DebugPrefix + '@Application = ' + @Application
   PRINT @DebugPrefix + '@StartDate = ' + CAST(@StartDate AS varchar)
   PRINT @DebugPrefix + '@EndDate = ' + CAST(@EndDate AS varchar)
   PRINT @DebugPrefix + '@FaultCode = ' + @FaultCode
   PRINT @DebugPrefix + '@FailureCategory = ' + @FailureCategory
   PRINT @DebugPrefix + '@ErrorType = ' + @ErrorType
END;


---------------------------------------------------------------
--	Select the faults.
---------------------------------------------------------------

	SELECT 
		f.[FaultID]
	  ,f.[NativeMessageID]
	  ,f.[ActivityID]
	  ,f.[Application]
	  ,f.[Description]
	  ,f.[ErrorType]
	  ,f.[FailureCategory]
	  ,f.[FaultCode]
	  ,f.[FaultDescription]
	  ,f.[FaultSeverity]
	  ,f.[Scope]
	  ,f.[ServiceInstanceID]
	  ,f.[ServiceName]
	  ,f.[FaultGenerator]
	  ,f.[MachineName]
	  ,f.[DateTime]
	  ,f.[ExceptionMessage]
	  ,f.[ExceptionType]
	  ,f.[ExceptionSource]
	  ,f.[ExceptionTargetSite]
	  ,f.[ExceptionStackTrace]
	  ,f.[InnerExceptionMessage]

	FROM dbo.Fault f 
	WHERE 
			 f.[FaultID] = isNull(@FaultID,FaultID)
	   AND   f.[Application] = isNull(@Application,[Application])
	   AND   f.[FailureCategory] =isNull(@FailureCategory, FailureCategory)
	   AND   f.ErrorType = isNull(@ErrorType,ErrorType)
	   AND   f.[FaultCode] = isNull(@FaultCode,FaultCode)
	   AND  f.[DateTime] between @startDate and @enddate
	   AND   f.[FaultSeverity] between 0 AND @MaxFaultSeverity 
	order by f.[DateTime] desc



-- CHECK FOR ERROR
SET @ErrorCode = @@Error;
IF (@ErrorCode <> 0) GOTO ERROR_HANDLER;
			
RETURN 0;

-- Handles errors.
ERROR_HANDLER:
IF (@ErrorCode <> 0)
BEGIN
    IF (@Debug > 0) 
		BEGIN
			PRINT @DebugPrefix + 'Error Code = ' + CAST(@ErrorCode AS varchar(10)) + ' occurred.';
			RETURN @ErrorCode
		END

    -- Don't return any evidence of what specific error occurred, i.e. 
    -- we want to ward off potential hackers.
    RETURN 1;
END;

SET NOCOUNT OFF;
